package com.jxtc.enterprise.admin.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxtc.enterprise.admin.dto.AdminOrderStatisticDTO;
import com.jxtc.enterprise.admin.service.AdminCompanyManagementService;
import com.jxtc.enterprise.admin.vo.AdminCompanyMoreDetailVO;
import com.jxtc.enterprise.admin.vo.AdminOrderVO;
import com.jxtc.enterprise.admin.vo.AdminViewCompanyDetailVO;
import com.jxtc.enterprise.common.aspectj.TokenRequired;
import com.jxtc.enterprise.common.mapper.AdminViewOrderMapper;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.common.vo.PaginationResponseVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 管理员视图，公司管理
 */
@RestController
@RequestMapping("/jxtc/enterprise/admin/companyManage")
@RequiredArgsConstructor
@Slf4j
@TokenRequired(role = TokenRequired.ROLE_ADMIN)
public class AdminCompanyManagementController {

    private final AdminCompanyManagementService adminViewCompanyManagementService;

    private final AdminViewOrderMapper orderAdminViewMapper;

    public static ThreadLocal<String> TL_REQUEST_ID = new ThreadLocal<>();

    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为包含订单列表的分页信息")
    @Parameter(name = "tenantName", description = "租户名称, 管理员视图，公司管理页面，新增一个 租户名 输入框作为查询条件")
    @Parameter(name = "companyName", description = "租户名称")
    @Parameter(name = "state", description = "公司状态【所有(1)/正常供餐(2)/停止供餐(3)/已删除(4)】", example = "1")
    @Parameter(name = "page", description = "当前页码，从 1（默认值）开始")
    @Parameter(name = "size", description = "每页显示的记录数，默认为 10")
    @Operation(summary = "1.2.1 管理员视图，分页查询租户所服务的公司列表", tags = "1.2 管理员公司管理", operationId = "1.2.1")
    @GetMapping("/queryCooperateCompanyByPage")
    public Result<PaginationResponseVO<AdminViewCompanyDetailVO>> queryCooperateCompaniesByPage(
            @RequestParam(required = false) String tenantName,
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false, defaultValue = "1") Integer state,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "10") int size) {
        String requestId = UUID.randomUUID().toString();
        // 每一次请求，生成一个唯一的请求id，将请求id放入到 ThreadLocal中，作为该接口实现逻辑中，调用栈中，各个栈帧 之间可共享的共享变量中，这样本次请求处理过程中，
        // 同一个调用栈中的各个栈帧对应的方法中，打印的requestId相同，便于查看日志时，通过唯一的requestId来将 散布在日志文件中的 日志串联起来
        log.info("requestId {}, admin view, /queryCooperateCompanyByPage, tenantName: {}, companyName: {}, state: {}", requestId, tenantName, companyName, state);
        PaginationResponseVO<AdminViewCompanyDetailVO> vo = adminViewCompanyManagementService.queryCompanyByPageAdminView(tenantName, companyName, state, page, size);
        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 接口1.2.2 根据公司id，查看某个公司详情
     * @return
     */
    @GetMapping("/queryCompanyDetailByCompanyId")
    public Result<?> queryCompanyDetailByCompanyId(@RequestParam(name = "companyId") String companyId) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, admin view, /queryCompanyDetailByCompanyId, companyId: {}", requestId, companyId);
        TL_REQUEST_ID.set(requestId);

        AdminCompanyMoreDetailVO companyDetailVO = adminViewCompanyManagementService.queryCompanyDetailById(companyId);

        Result<Object> resultVO = new Result<>();
        resultVO.setData(companyDetailVO);
        return resultVO;
    }

    @Operation(summary = "1.2.6 管理员视图，查询某个公司的订单", tags = {"1.2 管理员公司管理"}, operationId = "1.2.6")
    @GetMapping("/queryOrderByCompanyIdByPageAdminView")
    public Result<?> queryOrderByCompanyIdByPageAdminView(
            @RequestBody JSONObject requestBody) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, admin view, /adminView/queryOrderByCompanyIdByPageAdminView, requestBody: {}", requestId, requestBody);

        String companyId = requestBody.getString("companyId");
        String startDateTime = requestBody.getString("startDateTime");
        String endDateTime = requestBody.getString("endDateTime");
        int pageNo = requestBody.getInteger("pageNo");
        int pageSize = requestBody.getInteger("pageNo");

        Page<AdminOrderStatisticDTO> page = new Page<>(pageNo, pageSize);

        // 如果开始时间为空，则设置为最早日期
        if (startDateTime == null || startDateTime.isEmpty()) {
            startDateTime = "2024-01-01";
        }
        LocalDate startDate = LocalDateTimeUtil.parseDate(startDateTime);
        // 如果结束时间为空，则设置为当前日期的后一天；如果结束时间不为空，则将 yyyy-MM-dd 格式的时间转换成 LocalDate 类型
        LocalDate today = LocalDate.now();
        LocalDate endDate = today.plusDays(1);
        if (endDateTime != null && !endDateTime.isEmpty()) {
            endDate = LocalDateTimeUtil.parseDate(endDateTime);
        }
        // 结束日期增加 1 天，防止当天数据查询不到
        // LocalDate endDate = rowEndDate.plusDays(1);

        Page<AdminOrderStatisticDTO> result = orderAdminViewMapper.queryOrderStatisticAdminView(page, companyId, startDate, endDate);
        List<AdminOrderVO> records = result.getRecords().stream().map(AdminOrderVO::new).collect(Collectors.toList());

        log.info("requestId {}, admin view, /adminView/queryOrderByCompanyIdByPageAdminView, response successfully", requestId);
        PaginationResponseVO<AdminOrderVO> pageData =  new PaginationResponseVO<>(result.getTotal(), result.getCurrent(), records);
        return ResultGenerator.genSuccessResult(pageData);
    }

}
